<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 中天个人  ajie
 */
class ZtgrController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.ordNo") ? I("request.ordNo") : I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        // $isMobile = isMobile();
        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            //微信
            case 1:
            //微信H5
            case 2:
                $pay_bankcode = '2';
                break;

            //支付宝
            case 3:
            case 17: //原生
            case 4:
            case 18: //原生
                $pay_bankcode = '1';
                break;
            //银联扫码
            case 11:
            case 19:
            case 9:
                $pay_bankcode = '3';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $params = array(
            'merchantCode'   => $this->config['mch_id'], 	        //商户号：找客服提供
            'merchantOrderNo'    => $return['orderid'], 	//商户订单号：必传，订单唯一标示，作为订单结果通知的标识，可按照你们业务生成
            'payType'    => $pay_bankcode, 	                //付款类型：必传，1-支付宝、2-微信、3-云闪付、4-全民付、5-银行
            'payPrice'    => intval($return['amount']*100),               //付款金额：必传，以分为单位，例如：150元应该传递：15000
            'merchantRemark' => '手机充值卡',  	    //商户备注：可为空，作为付款说明，回调时会传递过去
            'callbackUrl'    => $return['notifyurl'], 	//异步通知地址：必传，作为订单结果通知地址，具体回调接口可参考回调示例
            'merchantName'    => 'dsfsf'            //商户名称：必传，作为付款码图片上的商户名称
        );

//签名字符串
        $string = "merchantName=" . $params['merchantName'] . "&merchantCode=" . $params['merchantCode'] . "&merchantOrderNo=" . $params['merchantOrderNo']
            . "&payPrice=" . $params['payPrice'] . "&payType=" . $params['payType'] . "&" . $this->config['signkey'];

//md5签名加密
        $params['sign'] = md5($string);


        $res = curl_json($this->config['gateway'], $params); //json提交
        $resp = json_decode($res,true);

        //var_dump('<pre/>',$params,$this->config['gateway'],$this->config['signkey'],$res,$resp);exit();

        $code = $resp['datas']['payPic'];

        if($code){

            $paytype = transArr( C("PAYTYPES"), "id");
            $this->assign("wap_url", $code);
            $this->assign("code_url", $code);
            $this->assign("title", $paytype[$this->config['paytype']]);
            $this->assign("return", $return);
           // $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));
//选择支付页面
            switch($this->config['paytype']){

                //支付宝扫码
                case 3:
                    //支付宝H5
                case 4:
                case 17:
                case 18:
                    if(isMobile()){

                        $this->display("WeiXin/alipaywap");
                    }else{
                        $this->display("WeiXin/alipay");
                    }
                    break;
                default:
                    $this->display("WeiXin/Pay");//收银台
            }
            exit();
        }

        if($resp['message']){
            $this->showmessage($resp['message'],['code'=>C("THIRDCODES.".$this->class)]);
        }

        $this->showmessage('获取支付连接失败！',['code'=>C("THIRDCODES.".$this->class)]);

    }



    //通知
    public function notifyurl(){
       // $this->debug_callback();

        //IP白名单
        if(!$this->checkip(getIP(),['211.110.66.234'])){
           exit("wrong");
        }

        //$p = json_decode(file_get_contents('php://input'),true);
        $p = I("get.");

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['merchantOrderNo'];

        //获取订单
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        /*M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
             "pay_orderid_rd"=>htmlspecialchars($p['order_no'])
        ));*/


        $real_amount =  $p['payPrice']/100;     //实际支付金额
        $pay_amount =  $find['pay_amount']; //商户提交订单金额

        if(abs($real_amount - $pay_amount) > 1){
            echo 'wrong_money'; exit;
        }

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>$this->class]);

        $res = $this->verify1($p,$this->config['signkey']);
        if(!$res){
            exit("sign_wrong");
        }

        if($p['noticeType'] !== "1"){
            exit("fail");
        }


        $this->async($find['pay_orderid'],"ok");
    }

    //验证签名
   public function verify1($params,$key){

        //签名字符串
        $string = "merchantName=" . urlencode($params['merchantName']) . "&merchantOrderNo=" . $params['merchantOrderNo']
            . "&noticeType=" . $params['noticeType'] . "&payPrice=" . $params['payPrice'] . "&payType=" . $params['payType'] . "&" . $key;
        //重新签名
        $sign = md5($string);
        //对比签名是否一致
        if(!empty($params['sign']) && $sign == $params['sign']){

            return true;
        }else{
            return false;
        }
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
